// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default {
  install(Vue, options) {
    Vue.prototype.getPdf = function (id, fileName) {
      let el = id || '#pdfDom';
      html2Canvas(document.querySelector(el), {
        allowTaint: true, //允许污染
        taintTest: true, //在渲染前测试图片(没整明白有啥用)
        useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用,下面解释)
        scale: 3
      }).then(function (canvas) {
          let contentWidth = canvas.width
          let contentHeight = canvas.height
          let pageWidth = $(el).width()
          let pageHeight = contentWidth / 592.28 * 841.89
          // 解决分页隔断问题
          let pageNum = Math.ceil((contentHeight - 100)/(pageHeight - 100));
          $('.jy-page').attr('style', 'height:'+pageHeight+'px;width:' + pageNum * pageWidth + 'px;column-count: '+pageNum+'');
          var baseDom = $('.jy-page').eq(0)
          if (pageNum > 1) {
            for (var i = 1; i < pageNum; i++) {
              $(el).append(baseDom.clone().css('left','-' + pageWidth * i + 'px'))
            }
          }
          $('.table-item-first').each(function () {
            if ($(this).text().length > 5) {
              let pipHeight = $(this).height()
              $(this).nextAll().height(pipHeight).css({'line-height':pipHeight + 'px'})
            } else {
              let pipHeight = $(this).height()
              $(this).nextAll().height(pipHeight).css({'line-height':pipHeight + 'px'})
            }
          })
          // end
          let leftHeight = contentHeight
          let position = 0
          let imgWidth = 595.28
          let imgHeight = 592.28 / contentWidth * contentHeight
          let pageData = canvas.toDataURL('image/jpeg', 1.0)
          let PDF = new JsPDF('', 'pt', 'a4')
          if (leftHeight < pageHeight) {
            PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          } else {
            while (leftHeight > 0) {
              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
              leftHeight -= pageHeight
              position -= 841.89
              if (leftHeight > 0) {
                PDF.addPage()
              }
            }
          }
          PDF.save(fileName + '.pdf')
        }
      )
    }
  }
}
